package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersControler {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserService userService;

    /**
     * 查询用户资料
     */
    @GetMapping
    public ResponseEntity users(Long userID) {
        if (userID == null) {
            userID = UserHolder.getUserId();
        }
        UserInfoVo userInfo = userInfoService.findById(userID);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 更新用户资料
     */
    @PutMapping
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo) {
        userInfo.setId(UserHolder.getUserId());
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 更新用户头像
     */
    @PostMapping("/header")
    public ResponseEntity header(MultipartFile headPhoto) throws IOException {
        Long userId = UserHolder.getUserId();
        userInfoService.updateHead(headPhoto, userId);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号- 1 发送短信验证码
     *
     * @return
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendVerificationCode() {
        String mobile = UserHolder.getMobile();
        userService.sendMsg(mobile);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号 - 2 校验验证码
     *
     * @param map
     * @return
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCode(@RequestBody Map<String, String> map) {
        String Code = map.get("verificationCode");
        String mobile = UserHolder.getMobile();
        Map verification = userService.checkVerificationCode(mobile, Code);
        return ResponseEntity.ok(verification);
    }

    /**
     * 修改手机号 - 3 保存
     */
    @PostMapping("/phone")
    public ResponseEntity phone(@RequestBody Map<String, String> map) {
        String newPhone = map.get("phone");
        Long userId = UserHolder.getUserId();
        userService.updatePhone(newPhone, userId);
        return ResponseEntity.ok(null);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    @GetMapping("/counts")
    public ResponseEntity counts() {
        Long userId = UserHolder.getUserId();
        Map map = userService.counts(userId);
        return ResponseEntity.ok(map);
    }
}
